package com.sunwhite.herostore.cmdhandler;

import com.sunwhite.herostore.common.BroadCaster;
import com.sunwhite.herostore.common.UserManager;
import com.sunwhite.herostore.entity.User;
import com.sunwhite.herostore.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

public class UserMoveToCmdHandler implements CmdHandler<GameMsgProtocol.UserMoveToCmd> {
    @Override
    public void handle(ChannelHandlerContext channelHandlerContext, GameMsgProtocol.UserMoveToCmd msg) {
        Integer userId = (Integer)channelHandlerContext.channel().attr(AttributeKey.valueOf("userId")).get();

        if (null == userId) {
            return;
        }

        GameMsgProtocol.UserMoveToCmd cmd = msg;
        //将用户当前的移动信息放入到用户信息中

        User user = UserManager.getUserById(userId);
        user.moveState.fromPosX=cmd.getMoveFromPosX();
        user.moveState.fromPosY=cmd.getMoveFromPosY();
        user.moveState.toPosX=cmd.getMoveToPosX();
        user.moveState.toPosY=cmd.getMoveToPosY();
        user.moveState.startTime=System.currentTimeMillis();
        //将需要计算位置的消息发送到前端
        GameMsgProtocol.UserMoveToResult.Builder resultBuilder = GameMsgProtocol.UserMoveToResult.newBuilder();
        resultBuilder.setMoveUserId(userId);
        resultBuilder.setMoveFromPosX(cmd.getMoveFromPosX());
        resultBuilder.setMoveFromPosY(cmd.getMoveFromPosY());
        resultBuilder.setMoveToPosX(cmd.getMoveToPosX());
        resultBuilder.setMoveToPosY(cmd.getMoveToPosY());
        resultBuilder.setMoveStartTime(user.moveState.startTime);
        GameMsgProtocol.UserMoveToResult userMoveToResult = resultBuilder.build();
        BroadCaster.broadCast(userMoveToResult);


    }
}
